package com.example.demo.api;

import com.example.demo.model.User;
import com.example.demo.mapper.UserMapper;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

@RestController
@Slf4j
public class UserAPI {
    @Resource
    UserMapper userMapper;

    @PostMapping("/login")
    @ResponseBody
    public Object login(String username, String password, HttpServletRequest req) {
        log.info("用户登录, username:{}, password:{}", username, password);
        if(!StringUtils.hasLength(username) || !StringUtils.hasLength(password)) {
            log.info("登录失败! 用户名或密码为空");
            return new User();
        }
        //1.先从数据库中查, 看username能否找到对应的user对象
        // 如果能找到看一下密码是否匹配
        User user = userMapper.selectByName(username);
        if(user == null || !user.getPassword().equals(password)) {
            //这两个条件具备一个, 就是登录失败, 同时返回一个空的对象即可
            log.info("登录失败! 用户名或密码错误! {}" , user );
            return new User();
        }

        //2.如果都匹配, 登录成功, 创建会话
        HttpSession session = req.getSession(true);
        session.setAttribute("user", user);
        user.setPassword("");
        return user;
    }

    @PostMapping("/register")
    @ResponseBody
    public Object register(String username, String password) {
        log.info("用户注册, username:{}, password:{}", username, password);
        User user = null;
        try {
            user = new User();
            user.setUsername(username);
            user.setPassword(password);
            int ret = userMapper.insert(user);
            log.info("注册 ret: {}", ret);
            user.setPassword("");
            return user;
        }catch (DuplicateKeyException e) {
            return new User();
        }
    }

    @GetMapping("/userInfo")
    @ResponseBody
    public Object getUserInfo(HttpServletRequest req) {
        //1.先从请求中获取对话
        HttpSession session = req.getSession(false);
        if(session == null) {
            //会话不存在, 用户尚未登录,此时返回一个空的对象
            log.info("当前获取不到 session 对象");
            return new User();
        }
        //2.从会话中获取到之前保存的用户对象
        User user = (User) session.getAttribute("user");
        if(user == null) {
            log.info("当前获取不到 user 对象");
            return new User();
        }
        user.setPassword("");
        return user;
    }
}
